package me.denger.database2Word.service;

import lombok.Getter;
import me.denger.database2Word.bean.Table;
import me.denger.database2Word.config.ConfigBean;
import me.denger.database2Word.inteface.DatabaseInterFace;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 只实现了基本的获取表名，可根据实际的效果进行重写
 *
 * @author 登琼
 */
public abstract class DatabaseBaseAbstract implements DatabaseInterFace {

    /**
     * 数据库连接
     */
    @Getter
    private Connection connection;
    /**
     * 数据库连接配置
     */
    @Getter
    private ConfigBean configBean;

    /**
     * @param configBean 数据库配置
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public DatabaseBaseAbstract(ConfigBean configBean) throws ClassNotFoundException, SQLException {
        connection(configBean);
    }

    /**
     * @param driver   驱动
     * @param url      链接路径
     * @param userName 用户名
     * @param password 密码
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public DatabaseBaseAbstract(String driver, String url, String userName, String password) throws ClassNotFoundException, SQLException {
        this.connection(new ConfigBean(driver, url, userName, password));
    }

    /**
     * 获取连接
     *
     * @param configBean 配置
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private void connection(ConfigBean configBean) throws ClassNotFoundException, SQLException {
        Class.forName(configBean.getDriver());
        connection = DriverManager.getConnection(configBean.getUrl(), configBean.getUserName(), configBean.getPassword());
        this.configBean = configBean;
    }

    @Override
    public List<Table> getTableNames(String tableNamePrefix) throws SQLException {

        List<Table> tableList = new ArrayList<>();
        // 获取数据库的元数据
        DatabaseMetaData db = connection.getMetaData();
        // 从元数据中获取到所有的表名
        try (ResultSet rs = db.getTables(connection.getCatalog(), configBean.getUserName().toUpperCase(), tableNamePrefix, new String[]{"TABLE"})) {
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                String remarks = rs.getString("REMARKS");
                tableList.add(new Table(tableName, remarks));
            }
        }
        return tableList;
    }

}
